﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Management.Automation;

using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.PowerShell;

namespace Mystery.SharePoint.PowerShell
{
	[Cmdlet("Add", "SPMHostsEntry")]
	public class AddHostsEntryCmdlet : SPCmdlet
	{
		/// <summary>
		/// The host name to use in the hosts file, can be of type http://server.com
		/// </summary>
		[Parameter(Mandatory = true)]
		public string HostName { get; set; }
		/// <summary>
		/// The IP Address of the host
		/// </summary>
		[Parameter(Mandatory = true)]
		public string IPAddress { get; set; }
		/// <summary>
		/// A comment to display together with the entry
		/// </summary>
		[Parameter(Mandatory=false)]
		public string Comment { get; set; }
        /// <summary>
        /// The list of servers to apply this operation on 
        /// </summary>
        [Parameter(Mandatory = true)]
        public string[] Servers { get; set; }

		protected override void InternalProcessRecord()
		{
			string host = HostName;
			Uri uri;
			// if we get a traditional url, extract the host name
			if (Uri.TryCreate(HostName, UriKind.Absolute, out uri) == true)
			{
				host = uri.Host;
			}

			Regex rx = new Regex(@"\s" + host + @"\s", RegexOptions.IgnoreCase);

            foreach (string server in this.Servers)
			{
				string path = Utils.CreateUncPath(server, 
					Environment.ExpandEnvironmentVariables("%WINDIR%\\system32\\drivers\\etc\\hosts"));

				bool found = false;

				foreach (string line in File.ReadAllLines(path))
				{
					if (rx.IsMatch(line) == true)
					{
						found = true;
						break;
					}
				}
				if (found == false)
				{
					base.Host.UI.WriteLine(string.Format(null, "Updating hosts file: {0}", path));
					base.Host.UI.WriteLine(string.Format(null, "IP Address: {0}", this.IPAddress));
					base.Host.UI.WriteLine(string.Format(null, "Host: {0}", host));
					base.Host.UI.WriteLine(string.Format(null, "Comment: {0}", this.Comment));

					string entry = string.Format("{0}{1}      {2}	#{3}", 
						Environment.NewLine, this.IPAddress, host, this.Comment);
					File.AppendAllText(path, entry);
				} 
			}  
		}
	}
}
